<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="商品列表"
      rowKey="id"
      :columns="columns"
      :requestApi="ProductApi.page"
      :dataCallback="dataCallback"
      :initParam="initParam"
      :searchCol="{ xs: 2, sm: 3, md: 4, lg: 6, xl: 8 }"
      :rowSelection="
        showSelection
          ? {
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
              type: selectionType
            }
          : undefined
      "
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" v-hasPermi="['sys:product:add']" @click="openDrawer('新增')">新增商品</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" v-hasPermi="['sys:product:edit']" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="success" link :icon="Check" v-hasPermi="['sys:product:up']" @click="openStateDialog('编辑', scope.row)" v-if="scope.row.status !== 1">商品上架</el-button>
        <el-button type="danger" link :icon="Bottom" v-hasPermi="['sys:product:down']" @click="openStateDialog('编辑', scope.row)" v-if="scope.row.status === 1"
          >商品下架</el-button
        >
      </template>
    </ProTable>
    <ProductDialog ref="dialogRef" />
    <ProductStateDialog ref="stateDialogRef" />
  </div>
</template>

<script setup lang="ts" name="ProductList">
import { ref, reactive, computed } from 'vue'
import { ColumnProps } from '@/components/ProTable/interface'
import ProTable from '@/components/ProTable/index.vue'
import { ProductApi } from '@/api/modules/product'
import { Bottom, Check, CirclePlus, EditPen } from '@element-plus/icons-vue'
import { ProductStatusList } from '@/configs/enum'
import ProductDialog from './components/ProductDialog.vue'
import ProductStateDialog from './components/ProductStateDialog.vue'

// const props = defineProps({
//   isShowHeader: {
//     type: Boolean,
//     default: true
//   }
// })
// 添加 props
interface Props {
  isShowHeader?: boolean
  showSelection?: boolean
  selectionLimit?: number
}

const props = withDefaults(defineProps<Props>(), {
  isShowHeader: true,
  showSelection: false,
  selectionLimit: 1
})

// 选择相关
const selectedRowKeys = ref<number[]>([])
const selectedList = ref<any[]>([])

// 计算选择类型
const selectionType = computed(() => {
  return props.selectionLimit === 1 ? 'radio' : 'checkbox'
})

// 选择变化事件
const onSelectChange = (keys: number[], rows: any[]) => {
  console.log('选择变化:', keys, rows)

  if (props.selectionLimit === 1 && keys.length > 1) {
    // 单选模式下，只保留最后一个选中的
    const lastKey = keys[keys.length - 1]
    const lastRow = rows.find((row) => row.id === lastKey)
    selectedRowKeys.value = [lastKey]
    selectedList.value = lastRow ? [lastRow] : []
  } else {
    selectedRowKeys.value = keys
    selectedList.value = rows
  }
}

// 表格配置项
const columns: ColumnProps[] = [
  { type: 'selection', fixed: 'left', width: 60 },
  {
    prop: 'name',
    label: '商品名称',
    search: { el: 'input' },
    minWidth: 150
  },
  {
    prop: 'price',
    label: '价格',
    minWidth: 100,
    render: (scope) => `¥${scope.row.price.toFixed(2)}`
  },
  {
    prop: 'sales',
    label: '销量',
    minWidth: 100
  },
  {
    prop: 'stock',
    label: '库存数量',
    minWidth: 100
  },
  {
    prop: 'status',
    label: '商品状态',
    enum: Object.values(ProductStatusList),
    search: { el: 'select' },
    tag: true,
    minWidth: 120
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200, isShow: props.isShowHeader }
]
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref()

defineExpose({
  proTable
})
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ isPublic: 0 })
// 处理返回数据格式
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  }
}

// 打开抽屉
const dialogRef = ref()
const openDrawer = (title: string, row: Partial<any> = {}) => {
  let params = {
    title,
    row: { ...row },
    isView: title === '查看',
    api: ProductApi.saveOrEdit,
    getTableList: proTable.value.getTableList,
    maxHeight: '300px'
  }
  dialogRef.value.acceptParams(params)
}

const stateDialogRef = ref()
const openStateDialog = (title: string, row: Partial<any> = {}) => {
  let params = {
    title,
    row: { ...row },
    isView: title === '查看',
    api: ProductApi.saveOrEdit,
    getTableList: proTable.value.getTableList,
    maxHeight: '150px'
  }
  stateDialogRef.value.acceptParams(params)
}
</script>
